import { Component } from '@angular/core';
import { AgRendererComponent } from '@ag-grid-community/angular';
import { ICellRendererParams } from '@ag-grid-community/core';
import { deepClone } from '../../../utils/utils';
import { ExpressionService } from '@core/services/expression/ExpressionService';

@Component({
  selector: 'apes-render-select',
  template: `
    <div class='render-select' [apes-tooltip]="this.getName(params.value)">{{this.getName(params.value)}}</div>
  `,
  styles: [`
    .render-select {
      overflow: hidden;
      text-overflow: ellipsis
    }
  `,
  ],
})
export class ApesRenderSelectComponent implements AgRendererComponent {
  value: any;
  params: ICellRendererParams;
  valueFormatter = '';

  constructor(private  expressionService: ExpressionService) {
  }

  refresh(params: any): boolean {
    return false;
  }

  agInit(params: ICellRendererParams): void {
    this.params = params;
    if (params.hasOwnProperty('colDef')) {
      this.valueFormatter = deepClone(params.colDef['valueFormatter']);
    } else {
      this.valueFormatter = deepClone(params.column['colDef']['valueFormatter']);
    }
  }

  getName(params) {
    if (params != null && params != '' && params != undefined) {
      this.value = '';
      if (typeof params == 'string') {
        params = JSON.parse(params);
        if (typeof params == 'object') {
          if (Array.isArray(params)) {
            params.forEach(item => {
              this.value = this.value + item.name + ';';
            });
          }
        }
        return this.value;
      }
      if (params instanceof Object) {
        if (Array.isArray(params)) {
          params.forEach(item => {
            let valueName = this.formatter(item, this.valueFormatter || 'value.name');
            this.value = this.value + valueName + ';';
          });
        } else {
          this.value = this.formatter(params, this.valueFormatter || 'value.name');
        }
      } else if (params instanceof Array) {
        params.forEach(item => {
          this.value = this.value + item.name + ';';
        });
      } else {
        this.value = this.formatter(params, this.valueFormatter || 'value.name');
      }
      return this.value;
    }
  }

  formatter(value: any, expression: string) {
    return this.expressionService.evaluate(expression, {
      context: '',
      model: '',
      value: value,
    });
  }
}
